package org.springblade.thingsphere.network.initialize;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springblade.thingsphere.CompositeProtocolSupport;
import org.springblade.thingsphere.manage.pojo.entity.ProtocolEntity;
import org.springblade.thingsphere.manage.service.IProtocolService;
import org.springblade.thingsphere.network.protocol.ProtocolAsset;
import org.springblade.thingsphere.network.protocol.ProtocolSupportDefinition;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author lhb
 * @date 2024/9/29 下午3:11
 */
@Slf4j
@Component
@Order(1)
public class LoadingProtocol implements ApplicationRunner {

	@Resource
	private IProtocolService protocolService;
	@Resource
	private ProtocolAsset protocolAsset;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		// 加载已启动的协议
		List<ProtocolEntity> list = protocolService.list(Wrappers.<ProtocolEntity>lambdaQuery()
			.eq(ProtocolEntity::getStatus, 1)
		);
		if (CollectionUtils.isEmpty(list)) {
			return;
		}
		for (ProtocolEntity protocol : list) {
			ProtocolSupportDefinition definition = new ProtocolSupportDefinition();
			definition.setId(protocol.getId());
			definition.setName(protocol.getName());
			definition.setClazzName(protocol.getClazzName());
			definition.setDescription(protocol.getDescription());
			definition.setJarPath(protocol.getJarPath());
			try {
				CompositeProtocolSupport load = protocolAsset.load(definition);
				log.info("load protocol : {} {}", load.getName(), load.getDescription());
			} catch (Exception e) {
				log.error("load protocol asset error", e);
			}
		}
	}
}
